package gnss_plugs

import (
	"dgo/goutils/gnss"
	"dgo/goutils/utils"
)

type GnssRtcmChecker struct {
	Id         string
	rtcmRawBuf *gnss.Rtcm3RawBuf
	cacheBuf   utils.BytesBuilder

	// rtcmMsgBuf 是整个RtcmBuf
	OnRtcmWholeBuf func(rtcmWholeBuf []byte) []byte
	OnCacheWrite   func(msgbuf []byte)
}

func NewGnssRtcmChecker() *GnssRtcmChecker {
	return &GnssRtcmChecker{
		rtcmRawBuf: gnss.NewRtcm32RawBuf(""),
	}
}

func (this *GnssRtcmChecker) FlushCache() {
	if this.cacheBuf.Len() > 0 {
		if this.OnCacheWrite != nil {
			this.OnCacheWrite(this.cacheBuf.Bytes())
		}
		this.cacheBuf.Reset()
	}
}

func (this *GnssRtcmChecker) check() {
	if this.rtcmRawBuf == nil {
		this.rtcmRawBuf = gnss.NewRtcm32RawBuf("")
	}
}

func (this *GnssRtcmChecker) Write(buf []byte) int {
	this.check()

	this.rtcmRawBuf.OutputWarning = false
	for i := 0; i < len(buf); i++ {
		r := this.rtcmRawBuf.InputBuf(buf[i])
		if r == gnss.RTCM_OK {
			rtcmBuf := this.rtcmRawBuf.GetRawBuf()
			if this.OnRtcmWholeBuf != nil {
				rtcmBuf = this.OnRtcmWholeBuf(rtcmBuf)
			}
			if rtcmBuf != nil && len(rtcmBuf) > 0 {
				this.cacheBuf.Write(rtcmBuf)
			}
			this.rtcmRawBuf.Reset()
		} else if r == gnss.RTCM_CRC_FAIL {
			utils.Log.Warnf("[%s]CRC校验失败", this.Id)
			this.rtcmRawBuf.Reset()
		} else if r == -1 {
			if this.rtcmRawBuf.GetSize() > 1 {
				utils.Log.Warnf("[%s]RTCM解码异常", this.Id)
			}
			this.rtcmRawBuf.Reset()
		}
	}

	return len(buf)
}
